// Copyright (c) 2020 Presto Labs Pte. Ltd.
// Author: donggu

#include "coin2/exchange/base/symbology/symbology_spec.h"

#include <boost/algorithm/string.hpp>

namespace impl {
SymbologySpecMap::SymbologySpecMap(const std::experimental::filesystem::path& filename) {
  namespace market = coin2::exchange::base::market;
  const auto table = toml::parse(filename).as_table();
  for (const auto& pair : table) {
    const auto& entry = pair.second.as_table();
    auto mea = MarketExchangeApi::FromStringNoThrow(pair.first);
    if (!mea.has_value()) {
      continue;
    }

    SymbologySpec spec;

    if (entry.find("feed_symbol") != entry.end()) {
      spec.feed_symbol = entry.at("feed_symbol").as_string();
    }

    if (entry.find("order_symbol") != entry.end()) {
      spec.order_symbol = entry.at("order_symbol").as_string();
    }

    if (entry.find("native_currency_lower_case") != entry.end()) {
      spec.native_currency_lower_case = entry.at("native_currency_lower_case").as_boolean();
    } else {
      spec.native_currency_lower_case = false;
    }

    if (entry.find("currencies") != entry.end()) {
      const auto& currencies = entry.at("currencies").as_table();
      for (const auto& [norm_name, native_name] : currencies) {
        std::string native_name_trimmed = native_name.as_string();
        boost::erase_all(native_name_trimmed, "\"");
        spec.currencies.insert(CurrencyPair(norm_name, native_name_trimmed));
      }
    }
    map_[mea.value()] = spec;
  }
}
}  // namespace impl
